package com.srv.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


public class ConfigProps {
	private static final String CONFIG_FILE_BASE_PATH = "/props/";
	
	private static final String ENVIRONMENT_DEFAULTS_FILE = "/config.properties";
	
	private static final String KEY_CURRENT_ENVIRONMENT = "currentEnvironment";
	
	private static ConfigProps mInstance = new ConfigProps();
	
	private Properties props;
	
	public static ConfigProps get(){
		return mInstance;
	}
	
	private ConfigProps(){
		try {
            InputStream is = ConfigProps.class.getResourceAsStream(ENVIRONMENT_DEFAULTS_FILE);
            if (is != null) {
            	Properties tmpProps = new Properties();
            	tmpProps.load(is);
            	String environment = tmpProps.getProperty(KEY_CURRENT_ENVIRONMENT);
            	
            	if(environment == null){
            		throw new IOException("the environment string is not found");
            	}
            	
            	is = ConfigProps.class.getResourceAsStream(CONFIG_FILE_BASE_PATH + environment);
            	props = new Properties();
            	props.load(is);
            }
        }
        catch (IOException e) {
        	System.out.println("the Class ConfigProps initialize failed");
        }
	}
	
	public String getString(String propname) {
		return props.getProperty(propname);
	}

	public String getString(String propname, String defValue) {
		String sval = props.getProperty(propname);
		if (sval == null) {
			return defValue;
		}

		return sval;
	}

	public boolean getBoolean(String propname, boolean defaultVal) {
		String sval = props.getProperty(propname);
		if (sval == null) {
			return defaultVal;
		}

		return Boolean.valueOf(sval).booleanValue();
	}

	public int getInt(String propname) {
		return getInt(propname, 0);
	}

	public int getInt(String propname, int defValue) {
		String sval = props.getProperty(propname);
		if (sval == null) {
			return defValue;
		}

		int val = defValue;
		try {
			val = Integer.parseInt(sval);
		}
		catch (NumberFormatException e) {
		}
		return val;
	}

	public double getDouble(String propname, double defValue) {
		String sval = props.getProperty(propname);
		if (sval == null) {
			return defValue;
		}

		double val = defValue;
		try {
			val = Double.parseDouble(sval);
		}
		catch (NumberFormatException e) {
		}
		return val;
	}

	public long getLong(String propname, long defValue) {
		String sval = props.getProperty(propname);
		if (sval == null) {
			return defValue;
		}

		long val = defValue;
		try {
			val = Long.parseLong(sval);
		}
		catch (NumberFormatException e) {
		}
		return val;
	}
}
